<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Requests\EVPIRequest;
use App\Http\Requests\ForgetRequest;
use App\Models\User;
use App\Repositories\UserRepository;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\AuthRegisterRequest;
use Illuminate\Support\Facades\Storage;


class UserController extends Controller
{
    protected $users;

    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
    public function store(AuthRegisterRequest $request)
    {

        $captchaKey = $request->captcha_key;

        $key = $request->type == 'phone' ? $request->phone_key : $request->email_key;

        $keyData = \Cache::get($key);
        $dataArr = $request->only([ 'name', 'password','asset_password' ]);
        if($request->type == 'phone') {
            $dataArr['phone'] = $keyData['payload']['phone'];
        }else {
            $dataArr['email'] = $keyData['payload']['email'];
        }

        // 判断有没有 ref_code
        $refCode = $request->ref_code;
        if ($refCode) {
            $parent = User::where('ref_code', $refCode)->firstOrFail();
        } else {
            $parent = User::firstOrFail();
        }
        //$childRefCode = str_random(6); // todo 验证码到时有重复的问题

        $dataArr['ref_code'] = $parent->generateRefCode();
        $dataArr['reg_ip'] = $request->getClientIp();
        $dataArr['password'] = Hash::make($dataArr['password']);
        $dataArr['asset_password'] = Hash::make($dataArr['asset_password']);

        $parent->children()->create($dataArr);

        // 清除缓存
        \Cache::forget($captchaKey);
        \Cache::forget($key);

        return $this->response->created();
    }

    public function phoneRegister()
    {
        
    }

    public function emailRegister()
    {
        
    }
    public function me()
    {
        return $this->response->item($this->user(), new UserTransformer());
    }
    // 完善信息
    public function evpi(EVPIRequest $request)
    {
        $dataArr = $request->only(['wechat_code','wechat_qrcode_url','bank_card','real_name','bank_name']);

        $avatar = $request->file('wechat_qrcode_url')->store('/public/' . date('Y-m-d') . '/avatars');
        //上传的头像字段avatar是文件类型
        $url = Storage::url($avatar);//就是很简单的一个步骤
        $dataArr['wechat_qrcode_url'] = $url;
        $user = auth('api')->user();
        $user->update($dataArr);
        return $this->response->created();

    }

    // 忘记密码
    public function forget(ForgetRequest $request)
    {
        $phone_key = $request->phone_key;

        $phoneData = \Cache::get($phone_key);
        $phone = $phoneData['payload']['phone'];

         User::where('phone',$phone)->update([
            'password'=>Hash::make($request->password)
        ]);
        return $this->response->created();
    }
}
